package com.adel.earthquake;

import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.adel.earthquake.Properties.Features;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;

public class MainActivity extends Activity {

	private Connection connection;
	private MenuItem menuRefresh;
	private ListView list;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		setTitle(R.string.app_name);
		list = (ListView) findViewById(R.id.list);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_refreh:
			if (connection.getStatus() == AsyncTask.Status.PENDING) {
				// My AsyncTask has not started yet
				connection.execute();
			} else if (connection.getStatus() == AsyncTask.Status.RUNNING) {
				// My AsyncTask is currently doing work in doInBackground()
			} else if (connection.getStatus() == AsyncTask.Status.FINISHED) {
				// My AsyncTask is done and onPostExecute was called
				connection = new Connection(this);
				connection.execute();
			}
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.activity_main, menu);
		menuRefresh = menu.findItem(R.id.menu_refreh);

		connection = new Connection(this);
		connection.execute();
		return true;
	}

	private class Connection extends AsyncTask<String, Void, String> {
		private Activity mActivity;

		public Connection(Activity mActivity) {
			this.mActivity = mActivity;
		}

		@Override
		protected String doInBackground(String... params) {
			try {
				HttpParams httpParameters = new BasicHttpParams();
				int timeoutConnection = 6000;
				HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
				int timeoutSocket = 6000;
				HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
				
				
				DefaultHttpClient client = new DefaultHttpClient(httpParameters);
				HttpGet request = new HttpGet(
						"http://earthquake.usgs.gov/earthquakes/feed/geojson/4.5/week");
				
				ResponseHandler<String> handleResponse = new BasicResponseHandler();
				String response = client.execute(request, handleResponse);
				return response;
			} catch (ClientProtocolException e) {
				show("Interner Error");
				Log.d("HTTPCLIENT", e.getLocalizedMessage());
			} catch (IOException e) {
				show("Interner Error");
				Log.d("HTTPCLIENT", e.getLocalizedMessage());
			}
			return null;
		}
		
		private void show(final String str){
			mActivity.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					if (menuRefresh != null) {
						menuRefresh.setActionView(null);
					}
					Toast.makeText(mActivity, str, Toast.LENGTH_LONG).show();
				}
			});
		}

		@Override
		protected void onPostExecute(String result) {
			if (result.equals(null)) {
				show("Interner Error");
				return;
			}

			Type type = new TypeToken<ArrayList<Features>>() {
			}.getType();
			try {
				final ArrayList<Features> features = new Gson().fromJson(
						new JSONObject(result).getJSONArray("features")
								.toString(), type);
				
				list.setAdapter(new ListCustonAdapter(mActivity, features));

			} catch (JsonSyntaxException e) {
				show("Interner Error");
				e.printStackTrace();
			} catch (JSONException e) {
				show("Interner Error");
				e.printStackTrace();
			}
			if (menuRefresh != null) {
				menuRefresh.setActionView(null);
			}
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			if (menuRefresh != null) {
				menuRefresh.setActionView(R.layout.actionbar_progress);
			}
			super.onPreExecute();
		}
	}

	public static class ListCustonAdapter extends BaseAdapter {
		private Activity mActivity;
		private ArrayList<Features> mFeatures = new ArrayList<Properties.Features>();

		public ListCustonAdapter(Activity mActivity,
				ArrayList<Features> mFeatures) {
			this.mActivity = mActivity;
			this.mFeatures = mFeatures;
		}

		@Override
		public int getCount() {
			return mFeatures.size();
		}

		@Override
		public Object getItem(int arg0) {
			return mFeatures.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int index, View view, ViewGroup arg2) {
			View mView = LayoutInflater.from(mActivity).inflate(
					R.layout.list_item, null);
			final Features feature = mFeatures.get(index);

			Date date = new Date();
			date.setTime((long) (feature.getProperties().getTime() * 1000));
			SimpleDateFormat dateFormat = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm");

			TextView tvTitle = (TextView) mView.findViewById(R.id.title);
			TextView tvSubtitle = (TextView) mView.findViewById(R.id.subtitle);
			TextView tvMag = (TextView) mView.findViewById(R.id.magnitude);

			tvTitle.setText(feature.getProperties().getPlace());
			tvSubtitle.setText("Depth : "
					+ feature.getGeometry().getCoordinates()[2]
					+ " Km. Date : " + dateFormat.format(date));
			tvMag.setText(feature.getProperties().getMag() + "");

			if (feature.getProperties().getMag() >= 7) {
				tvMag.setTextColor(Color.parseColor("#FE2E2E"));
			} else if (feature.getProperties().getMag() >= 5) {
				tvMag.setTextColor(Color.parseColor("#FE9A2E"));
			} else if (feature.getProperties().getMag() >= 3) {
				tvMag.setTextColor(Color.parseColor("#FFFF00"));
			} else {
				tvMag.setTextColor(Color.parseColor("#64FE2E"));
			}

			mView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					Intent intent = new Intent(arg0.getContext(),
							MyMapActivity.class);
					intent.putExtra(MyMapActivity.MAP_DATA, feature);
					arg0.getContext().startActivity(intent);
				}
			});
			return mView;
		}
	}
}
